package com.ipan.jfinal.validator;

import com.ipan.jfinal.controller.ResultDefineManager;
import com.ipan.kits.security.HexUtil;
import com.jfinal.captcha.Captcha;
import com.jfinal.captcha.CaptchaManager;
import com.jfinal.captcha.ICaptchaCache;
import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;

/**
 * 短信验证码_通用校验器
 * 
 * @author iPan
 * @date 2023-02-01
 */
public class SmsValidator extends Validator {
	
//	protected String k_sms_key = "smsKey";
	protected String k_mobile_key = "mobile";
	protected String k_sms_value = "smsValue";
	protected String k_error_key = "msg";
	protected String k_code_key = "code";
	
	public SmsValidator() {}

	@Override
	protected void validate(Controller c) {
		setShortCircuit(true); // 短路校验
		
//		String smsKey = c.getPara(k_sms_key);
		String mobile = c.getPara(k_mobile_key);
		validateRequired(k_mobile_key, k_error_key, "手机号不能为空");
		
		String smsValue = c.getPara(k_sms_value);
		ICaptchaCache captchaCache = CaptchaManager.me().getCaptchaCache();
		String smsKey = getSmsKey(mobile);
		Captcha captcha = captchaCache.get(smsKey);
		if (captcha != null && captcha.notExpired() && captcha.getValue().equalsIgnoreCase(smsValue)) {
			captchaCache.remove(captcha.getKey()); // 只在成功时候删除，支持重新输入正确的验证码；
		} else {
			addError(k_error_key, "手机验证码不正确"); // 标识校验失败
		}
	}
	
	protected String getSmsKey(String mobile) {
		return HexUtil.encodeHexStr("login_" + mobile);
	}

	@Override
	protected void handleError(Controller c) {
		c.setAttr(k_code_key, ResultDefineManager.me().getFail().getLeft()); // json状态码
		c.renderJson();
	}

}
